<template>
  <div>
    <!-- 可编辑带预览 -->
    <template v-if="!readonly">
      <el-upload
        class="upload-demo"
        name="uploadFile"
        :action="url"
        :headers="headers"
        :data="data"
        :accept="accept"
        :on-change="handleChange"
        :on-success="handleSuccess"
        :on-remove="handleRemove"
        :drag="isDrag"
        :limit="limit"
        :on-exceed="onExceed"
        :on-preview="onPreview"
        :file-list="fileList"
        :list-type="listType"
      >
        <el-button size="small" type="primary">点击上传</el-button>
        <div slot="tip" class="el-upload__tip" v-if="showTip">
          {{ `只能上传${accept}文件, 且不超过500MB` }}
        </div>
      </el-upload>
      <!-- 图片预览容器 -->
      <el-image
        ref="imgPreview"
        style="width: 0; height: 0; opacity: 0"
        :src="previewUrl"
        fit="cover"
        :preview-src-list="[previewUrl]"
      ></el-image>
    </template>
    <!-- 纯预览 -->
    <template v-else>
      <div class="enclosure">
        <el-tooltip
          effect="dark"
          :content="item.name"
          placement="top"
          v-for="(item, index) in fileList"
          :key="index"
        >
          <div class="enclosure-item">
            <img
              src="@/assets/img/word.webp"
              v-if="item.name.indexOf('.doc') > -1"
              alt=""
              @click="downloadFn(item.url)"
            />
            <img
              src="@/assets/img/excel.webp"
              v-else-if="item.name.indexOf('.xls') > -1"
              alt=""
              @click="downloadFn(item.url)"
            />
            <img
              src="@/assets/img/pdf.webp"
              v-else-if="item.name.indexOf('.pdf') > -1"
              alt=""
              @click="downloadFn(item.url)"
            />
            <el-image
              v-else
              :src="item.url"
              fit="cover"
              :preview-src-list="[item.url]"
            ></el-image>
            <div class="enclosure-name">{{ item.name }}</div>
          </div>
        </el-tooltip>
      </div>
    </template>
  </div>
</template>
<script>
import requestUrl from '@/core/http/requestUrl';
import { getToken, objectToQueryString } from '@/utils';
const imgArr = ['.jpg', '.jpeg', '.png'];
const defaultAccept = '.jpg, .jpeg, .png, .txt, .pdf, .doc, .docx, .xls, .xlsx';
export default {
  // 1.项目立项 2.合同上传 3.商机投标 4.资质盖章申请 5.盖章申请 6.用车申请 7.私车公用申请 8.合同盖章申请 9.商机任务成果交付 10.合同归档扫描件 11项目任务成果交付 12 项目复盘客户反馈表  13.项目复盘其他附件
  props: {
    accept: {
      type: String,
      default: defaultAccept
    },
    limit: {
      type: Number,
      default: 1
    },
    value: {
      type: Array,
      default: () => []
    },
    listType: {
      type: String,
      default: 'text'
    },
    isDrag: {
      type: Boolean,
      default: false
    },
    showTip: {
      type: Boolean,
      default: true
    },
    // 是否为纯预览
    readonly: {
      type: Boolean,
      default: false
    },
    // 模块区分
    // 1-项目；2-合同
    fielState: {
      type: String,
      default: '1'
    },
    // id: 个模块id
    id: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      // 上传的地址
      url: requestUrl('admin/app/leave/uploads'),
      // 下载的地址
      downLoadUrl: requestUrl('admin/app/leave/downloads'),
      // 预览的地址
      previewUrl: '',
      // 设置上传的请求头部
      headers: { Authorization: getToken() },
      data: {
        fieldName: 'filePath',
        asImage: false
      },
      fileList: []
    };
  },
  created () {
    console.log('----', this.fileList);
    this.$set(this.data, 'fielState', this.fielState);
  },
  computed: {
    isImg () {
      return name => {
        const fileName = name;
        const fileType = fileName?.substring(fileName?.lastIndexOf('.'));
        return imgArr.includes(fileType);
      }
    }
  },
  model: {
    event: 'changeFile'
  },
  watch: {
    value: {
      handler (val) {
        console.log('传进来', val);
        if (this.readonly) {
          this.fileList = this.getStaticPreviewUrl(val);
          return false;
        }
        this.fileList = val;
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    // 预览
    onPreview (file) {
      this.previewUrl = this.getPreviewUrl(file);
      if (!this.isImg(file.name)) {
        this.downloadFn(this.previewUrl);
      } else {
        this.$refs.imgPreview.showViewer = true;
      }
    },
    // 获取纯预览的list数据
    getStaticPreviewUrl (list) {
      return (list || []).map(v => {
        return {
          name: v.name,
          url: this.getPreviewUrl(v)
        }
      });
    },
    // 获取预览url
    getPreviewUrl (item) {
      return `${this.downLoadUrl}?${objectToQueryString({
        id: this.id,
        fieldName: 'filePath',
        filename: item.filename,
        fielState: this.fielState,
        asImage: this.isImg(item.name),
        Authorization: getToken()
      })}`
    },
    // 下载文件
    downloadFn (url) {
      window.location.href = url;
    },
    // 超出限制
    onExceed () {
      this.$message.error(`最多上传${this.limit}个文件，请删除后重新上传！`)
    },
    // 文件change函数
    handleChange (file, fileList) {
      this.$set(this.data, 'asImage', this.isImg(file.name));
    },
    /**
     * 上传文件-成功
    */
    handleSuccess (res, file, fileList) {
      fileList.length && fileList.pop();
      fileList.push({
        ...(res?.data || {}),
        uid: file.uid
      });
      console.log('上传文件-成功', fileList);
      this.$emit('changeFile', fileList);
    },
    /**
     * 上传文件-删除
     */
    handleRemove (file, fileList) {
      console.log('上传文件-删除', fileList);
      this.$emit('changeFile', fileList)
    }
  }
};
</script>
<style lang="scss" scoped>
.el-upload__tip {
  position: relative;
  left: 8px;
  top: 8px;
  display: inline;
}
.enclosure {
  display: flex;
  flex-wrap: wrap;
  .enclosure-item {
    flex-shrink: 0;
    width: 80px;
    margin-right: 20px;
    margin-bottom: 15px;
    img {
      width: 50px;
      height: 50px;
      object-fit: cover;
      margin: 0 auto;
      display: block;
    }
    .enclosure-name {
      width: 100%;
      text-align: center;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
  }
}
</style>
